<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="800px"
    @close="handleClose"
  >
    <el-row :gutter="20">
      <!-- 部门树 -->
      <el-col :span="8">
        <div class="department-tree">
          <div class="section-title">部门列表</div>
          <el-input
            v-model="deptFilterText"
            placeholder="搜索部门"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-tree
            ref="deptTreeRef"
            :data="deptTreeData"
            node-key="id"
            :props="deptProps"
            :filter-node-method="filterDeptNode"
            :expand-on-click-node="false"
            @node-click="handleDeptNodeClick"
          />
        </div>
      </el-col>
      
      <!-- 用户列表 -->
      <el-col :span="16">
        <div class="user-list">
          <div class="section-title">用户列表</div>
          <el-input
            v-model="userFilterText"
            placeholder="搜索用户"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-table
            ref="userTableRef"
            :data="userList"
            height="300"
            row-key="id"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="username" label="用户名" width="120" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column prop="phone" label="电话" width="120" />
          </el-table>
          <el-pagination
            v-model:current-page="userPage.current"
            v-model:page-size="userPage.size"
            :total="userPage.total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="pagination"
          />
        </div>
      </el-col>
    </el-row>
    
    <!-- 已选用户 -->
    <div class="selected-users" v-if="multiple && selectedUsers.length > 0">
      <div class="section-title">已选择 ({{ selectedUsers.length }})</div>
      <el-tag
        v-for="user in selectedUsers"
        :key="user.id"
        closable
        @close="removeSelectedUser(user)"
        class="user-tag"
      >
        {{ user.name }}
      </el-tag>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'

// 定义属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '选择用户'
  },
  multiple: {
    type: Boolean,
    default: false
  },
  selected: {
    type: Array,
    default: () => []
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'confirm', 'close'])

// 响应式数据
const visible = ref(false)
const deptFilterText = ref('')
const userFilterText = ref('')
const deptTreeData = ref([])
const userList = ref([])
const selectedUsers = ref([])
const deptTreeRef = ref()
const userTableRef = ref()

// 部门树配置
const deptProps = {
  label: 'name',
  children: 'children'
}

// 用户分页
const userPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 监听组件显示
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val
    if (val) {
      initDialog()
    }
  }
)

// 监听部门搜索
watch(deptFilterText, (val) => {
  deptTreeRef.value?.filter(val)
})

// 初始化对话框
const initDialog = async () => {
  selectedUsers.value = [...props.selected]
  await loadDeptTree()
  await loadUserList()
  
  // 如果是多选模式，设置已选中项
  if (props.multiple) {
    nextTick(() => {
      selectedUsers.value.forEach(user => {
        const row = userList.value.find(item => item.id === user.id)
        if (row) {
          userTableRef.value?.toggleRowSelection(row, true)
        }
      })
    })
  }
}

// 加载部门树
const loadDeptTree = async () => {
  try {
    // 模拟API调用 - 替换为实际API
    const response = await fetchDeptTree()
    deptTreeData.value = response.data
  } catch (error) {
    console.error('加载部门数据失败:', error)
  }
}

// 加载用户列表
const loadUserList = async (deptId = null) => {
  try {
    // 模拟API调用 - 替换为实际API
    const params = {
      page: userPage.current,
      size: userPage.size,
      deptId: deptId,
      keyword: userFilterText.value
    }
    
    const response = await fetchUserList(params)
    userList.value = response.data.records
    userPage.total = response.data.total
  } catch (error) {
    console.error('加载用户数据失败:', error)
  }
}

// 部门节点过滤
const filterDeptNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}

// 部门节点点击
const handleDeptNodeClick = (data) => {
  userPage.current = 1
  loadUserList(data.id)
}

// 分页变化
const handleSizeChange = (val) => {
  userPage.size = val
  loadUserList()
}

const handleCurrentChange = (val) => {
  userPage.current = val
  loadUserList()
}

// 用户选择变化
const handleSelectionChange = (selection) => {
  if (props.multiple) {
    selectedUsers.value = selection
  }
}

// 移除已选用户
const removeSelectedUser = (user) => {
  const index = selectedUsers.value.findIndex(item => item.id === user.id)
  if (index > -1) {
    selectedUsers.value.splice(index, 1)
    const row = userList.value.find(item => item.id === user.id)
    if (row) {
      userTableRef.value?.toggleRowSelection(row, false)
    }
  }
}

// 确认选择
const handleConfirm = () => {
  let result = []
  if (props.multiple) {
    result = selectedUsers.value
  } else {
    // 单选模式从表格选中项中取第一个
    const selection = userTableRef.value?.getSelectionRows()
    if (selection && selection.length > 0) {
      result = selection[0]
    }
  }
  
  emit('confirm', result)
  handleClose()
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
  emit('close')
  resetForm()
}

// 重置表单
const resetForm = () => {
  deptFilterText.value = ''
  userFilterText.value = ''
  userPage.current = 1
  selectedUsers.value = []
  if (userTableRef.value) {
    userTableRef.value.clearSelection()
  }
}

// 模拟API调用函数 - 需要替换为实际API
const fetchDeptTree = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: [
          {
            id: 1,
            name: '总公司',
            children: [
              {
                id: 2,
                name: '技术部',
                children: [
                  { id: 4, name: '前端组' },
                  { id: 5, name: '后端组' }
                ]
              },
              {
                id: 3,
                name: '销售部',
                children: [
                  { id: 6, name: '国内销售' },
                  { id: 7, name: '国际销售' }
                ]
              }
            ]
          }
        ]
      })
    }, 300)
  })
}

const fetchUserList = (params) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 模拟用户数据
      const mockUsers = [
        { id: 1, name: '张三', username: 'zhangsan', email: 'zhangsan@example.com', phone: '13800138001' },
        { id: 2, name: '李四', username: 'lisi', email: 'lisi@example.com', phone: '13800138002' },
        { id: 3, name: '王五', username: 'wangwu', email: 'wangwu@example.com', phone: '13800138003' },
        { id: 4, name: '赵六', username: 'zhaoliu', email: 'zhaoliu@example.com', phone: '13800138004' },
        { id: 5, name: '钱七', username: 'qianqi', email: 'qianqi@example.com', phone: '13800138005' }
      ]
      
      const records = mockUsers.slice((params.page - 1) * params.size, params.page * params.size)
      
      resolve({
        data: {
          records,
          total: mockUsers.length
        }
      })
    }, 300)
  })
}

// 挂载时初始化
onMounted(() => {
  visible.value = props.modelValue
})
</script>

<style scoped>
.department-tree,
.user-list {
  height: 400px;
  display: flex;
  flex-direction: column;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.search-input {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 15px;
  justify-content: flex-end;
}

.selected-users {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.user-tag {
  margin-right: 10px;
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>


<!-- 

<template>
  <div>
    <el-button @click="showDialog = true">选择用户</el-button>
    
    <user-select-dialog
      v-model="showDialog"
      :multiple="true"
      :selected="selectedUsers"
      @confirm="handleUserSelect"
    />
    
    <div v-if="selectedUsers.length > 0">
      <h3>已选择用户:</h3>
      <el-tag 
        v-for="user in selectedUsers" 
        :key="user.id"
        style="margin-right: 10px;"
      >
        {{ user.name }}
      </el-tag>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import UserSelectDialog from './components/user-select-dialog.vue'

const showDialog = ref(false)
const selectedUsers = ref([])

const handleUserSelect = (users) => {
  selectedUsers.value = users
  console.log('选中的用户:', users)
}
</script> -->